import DictService from "@/store/dict/dict.service";
import _ from "lodash";
import LocalStorageUtil from "@/utils/local-storage-util";
import i18n from "@/i18n";
import {I18nEnum} from "@/common/enum/common.enum";

const state = () => ({
	// 数据字典
	dict: LocalStorageUtil.getObjectItem('dict'),
	// 文件路径前缀
	urlPrefix: LocalStorageUtil.getItem('urlPrefix'),
	// 国际化列表
	i18nList: LocalStorageUtil.getItem('i18nList'),
})
const mutations = {
	//提交数据字典
	dict: (dictState, data) => {
		dictState.dict = data;
	},
	//提交文件路径前缀
	urlPrefix: (dictState, data) => {
		dictState.urlPrefix = data;
	},

	// 设置i18n并提交
	i18n(dictState, data) {
		let enUS = {}, zhCN = {}, zhTW = {};
		let list = data.map(item => {
			if (item.language === I18nEnum.enUS) {
				enUS[item.key] = item.value;
			}
			if (item.language === I18nEnum.zhCN) {
				zhCN[item.key] = item.value;
			}
			if (item.language === I18nEnum.zhTW) {
				zhTW[item.key] = item.value;
			}
			return {key: item.key, value: item.value, language: item.language, type: item.type}
		})
		i18n.mergeLocaleMessage(I18nEnum.enUS, enUS);
		i18n.mergeLocaleMessage(I18nEnum.zhCN, zhCN);
		i18n.mergeLocaleMessage(I18nEnum.zhTW, zhTW);
		dictState.i18nList = list;
		LocalStorageUtil.addItem('i18nList', list);
	},
	// 清除字典
	clearDict(dictState, data){
		LocalStorageUtil.deleteItem('i18nList');
		LocalStorageUtil.deleteItem('dict');
		dictState.dict = null;
		dictState.i18nList = null;
	}

}
const actions = {
	//获取所有数据字典（平铺）;
	dict({commit}) {
		let dict = LocalStorageUtil.getItem('dict');
		if (!_.isEmpty(dict)) {
			return commit('dict', dict);
		}
		DictService.getDict().then(res => {
			if (res.status === 200) {
				let data = res.data || [];
				let commitData = data.map(item => {
					return {
						name: item.name,
						value: item.value,
						code: item.code,
						parentCode: item.parentCode,
						tid: item.tid,
						parentId: item.parentId,
						desc: item.desc,
					}
				})
				commit('dict', commitData);
				LocalStorageUtil.addItem('dict', commitData);
			}
		})
	},

	//获取i18n字典并添加;
	i18n({commit}) {
		let i18nList = LocalStorageUtil.getObjectItem('i18nList');
		if (!_.isEmpty(i18nList)) {
			return commit('i18n', i18nList);
		}
		return DictService.getAllSysI18n().then(res => {
			if (res.status === 200) {
				commit('i18n', res.data);
			}
		})
	},

	//获取文件路径前缀;
	urlPrefix({commit}) {
		let urlPrefix = LocalStorageUtil.getItem('urlPrefix');
		if (!_.isEmpty(urlPrefix)) {
			return commit('urlPrefix', urlPrefix);
		}
		DictService.getUrlPrefix().then(res => {
			if (res.status === 200) {
				commit('urlPrefix', res.data);
				LocalStorageUtil.addItem('urlPrefix', res.data);
			}
		})
	},
	// 清除字典
	clearDict({commit}){
		commit('clearDict')
	}

};
const getters = {
	dict(dictState) {
		return dictState.dict
	},
	urlPrefix(dictState) {
		return dictState.urlPrefix
	},
	i18n(dictState) {
		return dictState.i18nList
	}
}
export default {state, getters, mutations, actions}

